<template>
  <div class="categories">
    <el-button @click="showAddDialog" plain type="success" class="addBtn">添加分类</el-button>
    <!-- 表格 -->
    <el-table :data="categoryList" row-key="cat_id"
     element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(255, 255, 255, 0.9)"
      v-loading="isLoading"

    >
      <el-table-column label="分类名称" prop="cat_name"></el-table-column>
      <el-table-column label="是否有效">
        <template v-slot="{row}">
          {{row.cat_deleted?"否":"是"}}
        </template>
      </el-table-column>
      <el-table-column label="层级" prop="cat_level"></el-table-column>
      <el-table-column label="操作">
        <template v-slot="{row}">
           <el-button size="small" plain type="primary" icon="el-icon-edit"></el-button>
          <el-button @click="delList(row.cat_id)" size="small" plain type="danger" icon="el-icon-delete"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
     <el-pagination
     background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagenum"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>

    <!-- 添加对话框 -->
    <el-dialog title="添加分类" :visible.sync="addVisible" width="40%">
    <el-form  :rules="rules" :model="form" ref="form" label-width="80px">
    <el-form-item label="父类名称" prop="cat_name" >
      <el-input v-model="form.cat_name" placeholder="请输入分类名称"></el-input>
    </el-form-item>

    <el-form-item label="父级名称"  prop="cat_pid">
      <el-cascader
      ref="cascader"
      clearable
    v-model="form.cat_pid"
    :options="options"
    :props="props"
    ></el-cascader>

    </el-form-item>
  </el-form>
  <template v-slot:footer>
  <div class="dialog-footer">
    <el-button @click="addVisible = false">取 消</el-button>
    <el-button type="primary" @click="addCategory">确 定</el-button>
  </div>
  </template>
</el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      pagenum: 1,
      pagesize: 5,
      categoryList: [],
      total: 0,
      addVisible: false,
      isLoading: false,
      form: {
        cat_pid: [],
        cat_name: '',
        cat_level: ''
      },
      rules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: ['change', 'blur'] }
        ]
      },
      options: [],
      props: {
        expandTrigger: 'hover', // 配置触发的方式, 为hover触发
        value: 'cat_id', // value是将来要提交给后台的id
        label: 'cat_name', // 配置显示的文字
        children: 'children', // 配置子集的展开属性名
        checkStrictly: true // 可以选中任意一级
      }
    }
  },
  created () {
    this.getCategoryList()
  },
  methods: {
    async getCategoryList () {
      this.isLoading = true
      const { data, meta } = await this.$axios.get('categories', {
        params: {
          type: 3,
          pagenum: this.pagenum,
          pagesize: this.pagesize
        }
      })
      if (meta.status === 200) {
        this.categoryList = data.result
        this.total = data.total
      }
      this.isLoading = false
    },
    handleSizeChange (val) {
      // console.log(`每页 ${val} 条`)
      this.pagesize = val
      this.pagenum = 1
      this.getCategoryList()
    },
    handleCurrentChange (val) {
      // console.log(`当前页: ${val}`)
      this.pagenum = val
      this.getCategoryList()
    },
    async showAddDialog () {
      this.addVisible = true
      const { meta, data } = await this.$axios.get('categories?type=2')
      // console.log(res)
      if (meta.status === 200) {
        this.options = data
      } else {
        this.$success.error(meta.msg)
      }
    },
    // 点击确认，提交
    async addCategory () {
      try {
        await this.$refs.form.validate()
        const { meta, data } = await this.$axios.post('categories', {
          cat_pid: this.form.cat_pid[this.form.cat_pid.length - 1] || 0,
          cat_name: this.form.cat_name,
          cat_level: this.form.cat_pid.length

        })
        if (meta.status === 201) {
          this.$message.success(meta.msg)
          this.addVisible = false
          this.$refs.form.resetFields()
          this.getCategoryList()
        } else {
          this.$message.error(meta.msg)
        }
      } catch (e) {
        console.log(e)
      }
    },
    // 点击删除
    async delList (id) {
      try {
        await this.$confirm('您确认要删除吗？', '温馨提示', {
          type: 'warning'
        })
        // console.log(id)

        const { meta } = await this.$axios.delete(`categories/${id}`)
        // console.log(res)

        if (meta.status === 200) {
          this.$message.success(meta.msg)
          if (this.categoryList.length === 1 && this.pagenum > 1) {
            this.pagenum--
          }
          this.getCategoryList()
        } else {
          this.$message.error(meta.msg)
        }
      } catch (err) {
        console.log(err)
      }
    }
  },
  watch: {
    'form.cat_pid' (newValue) {
      // 只要用户选择了对应的级联选择器的内容, 应该隐藏
      this.$refs.cascader.dropDownVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.addBtn{
  margin-bottom: 10px;
}
.el-pagination{
  margin-top: 10px;
}
</style>
